package com.css.zfzx.fxpg.modules.evaluationmap.download.controller;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.base.response.RestResponse;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.zfzx.fxpg.common.utils.ZipDownloadUtil;
import com.css.zfzx.fxpg.modules.evaluationmap.download.repository.entity.FxEvaluationMapDownloadEntity;
import com.css.zfzx.fxpg.modules.evaluationmap.download.service.FxEvaluationMapDownloadService;
import com.css.zfzx.fxpg.modules.evaluationmap.download.viewobjects.FxEvaluationMapDownloadQueryParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zyb
 * @date 2020-12-19
 */
@Slf4j
@RestController
@RequestMapping("/fx/fxEvaluationMapDownload")
public class FxEvaluationMapDownloadController {
    @Autowired
    private FxEvaluationMapDownloadService PGAResultMapService;

    @GetMapping("/queryEvaluationMapDownloads")
    public RestResponse queryHddcDResultmaptables(HttpServletRequest request, FxEvaluationMapDownloadQueryParams queryParams) {
        RestResponse response = null;
        try {
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            String sort=request.getParameter("sort");
            String order=request.getParameter("order");
            JSONObject jsonObject = PGAResultMapService.queryHddcDResultmaptables(queryParams, curPage, pageSize,sort,order);
            response = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @GetMapping("{id}")
    public RestResponse getHddcDResultmaptable(@PathVariable String id) {
        RestResponse response = null;
        try {
            FxEvaluationMapDownloadEntity hddcDResultmaptable = PGAResultMapService.getHddcDResultmaptable(id);
            response = RestResponse.succeed(hddcDResultmaptable);
        } catch (Exception e) {
            String errorMessage = "获取失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @PostMapping
    public RestResponse saveHddcDResultmaptable(@RequestBody FxEvaluationMapDownloadEntity hddcDResultmaptable) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            PGAResultMapService.saveHddcDResultmaptable(hddcDResultmaptable);
            json.put("message", "新增成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "新增失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;

    }

    @PutMapping
    public RestResponse updateHddcDResultmaptable(@RequestBody FxEvaluationMapDownloadEntity hddcDResultmaptable) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            PGAResultMapService.updateHddcDResultmaptable(hddcDResultmaptable);
            json.put("message", "修改成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "修改失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @DeleteMapping
    public RestResponse deleteHddcDResultmaptables(@RequestParam List<String> ids) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            PGAResultMapService.deleteHddcDResultmaptables(ids);
            json.put("message", "删除成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "删除失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @GetMapping("/getValidDictItemsByDictCode/{dictCode}")
    public RestResponse getValidDictItemsByDictCode(@PathVariable String dictCode) {
        RestResponse restResponse = null;
        try {
            restResponse = RestResponse.succeed(PGAResultMapService.getValidDictItemsByDictCode(dictCode));
        } catch (Exception e) {
            String errorMsg = "字典项获取失败!";
            log.error(errorMsg, e);
            restResponse = RestResponse.fail(errorMsg);
        }
        return restResponse;
    }

    /**
     * 上传附件
     * @param file
     * @param filenumber
     * @return
     */
//    @PostMapping("/upload")
//    public RestResponse upload(@RequestParam("file") MultipartFile file, @RequestParam("filenumber")String filenumber) {
//        RestResponse response = null;
//        JSONObject json = new JSONObject();
//        try{
//            int mag=hddcDResultmaptableService.upload(file,filenumber);
//            if (mag==2) {
//                json.put("message", "上传成功!");
//            }else if (mag==0){
//                json.put("message", "编号已存在!");
//            }
//            else if (mag==1){
//                json.put("message", "上传失败!");
//            }
//            response = RestResponse.succeed(json);
//        }catch (Exception e){
//            String errorMessage = "上传失败!";
//            log.error(errorMessage,e);
//            response = RestResponse.fail(errorMessage);
//        }
//        return response;
//    }


    //获取配置文件的上传文件路径
    @Value("${file.upload.path}")
    private String uploadPath;
    @GetMapping("/download")
    public RestResponse downloadFile(HttpServletResponse response,
                                     @RequestParam String province, @RequestParam String city, @RequestParam String area,
                                     @RequestParam String idCondition, @RequestParam String filenameCondition) {
        String _uploadPath = uploadPath.substring(0, uploadPath.indexOf("fujian") + 6) + "/fxpg/";
        File file = new File(_uploadPath);
        File[] files = file.listFiles();
        if (files == null) {
            return RestResponse.fail("下载失败，该目录下不存在文件");
        }
        //String province = queryParams.getProvince(), city = queryParams.getCity(), area = queryParams.getArea(), affiliatedFileName = queryParams.getFilename();
        //String tempFileName = (province == "" ? "0" : province) + "_" + (city == "" ? "0" : city) + "_" + (area == "" ? "0" : area) + "_" + (affiliatedFileName == "" ? "0" : affiliatedFileName);
        String tempFileName = filenameCondition;
        String _temp = "";
        List<File> _files = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            _temp = files[i].getName();
            boolean ff = _temp.indexOf(province) != -1 && _temp.indexOf(city) != -1 && _temp.indexOf(area) != -1;
            if ((_temp.indexOf(tempFileName) != -1 || _temp.indexOf(idCondition) != -1)) _files.add(files[i]);
            //if (_temp.indexOf(tempFileName) != -1) _files.add(files[i]);
        }
        List<File> zipFiles = _files;
        //List<File> zipFiles = new ArrayList<>(Arrays.asList(files));
        StringBuffer sb = new StringBuffer();
        if (!CollectionUtils.isEmpty(zipFiles)) {
            String zipName = tempFileName + ".zip";
            //String msg = ZipDownloadUtil.zipDownload(response, _uploadPath, zipName, zipFiles);
            String msg = ZipDownloadUtil.downFile(response, _uploadPath, zipName);
            sb.append(msg);
            return null;
        } else {
            /*sb.append("没有可下载文件");
            return RestResponse.succeed(sb);*/
            String zipName = 0 + ".zip";
            String msg = ZipDownloadUtil.zipDownload(response, _uploadPath, zipName, new ArrayList<File>());
            return null;
        }
    }
}